#pragma once
#include <iostream>
#include <string>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include "nocopy.hpp"
#include "Log.hpp"

using namespace log_ns;

enum
{
    SOCKET_ERROR = 1,
    BIND_ERROR
};

class UdpServer : public nocopy
{
public:
    UdpServer(uint16_t localport):_sockfd(-1), _localport(localport)
    {}

    void init()
    {
        // 1. 创建 socket 文件描述符
        _sockfd = ::socket(AF_INET, SOCK_DGRAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "sockfd error\n");
            exit(SOCKET_ERROR);
        }
        LOG(DEBUG, "sockfd create sucess, sockfd: %d\n", _sockfd);

        // 2. 绑定端口号
        struct sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(_localport);
        local.sin_addr.s_addr = INADDR_ANY;
        int n = ::bind(_sockfd, (sockaddr*)&local, sizeof(local));
        if(n < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(DEBUG, "socket bind sucess\n");
    }

    void start()
    {
        _isrunning = true;
        char inbuffer[1024];
        while (_isrunning)
        {
            struct sockaddr_in peer;
            socklen_t len = sizeof(peer);
            ssize_t n = recvfrom(_sockfd, inbuffer, sizeof(inbuffer) -1, 0, (struct sockaddr*)&peer, &len);
            if (n > 0)
            {
                inbuffer[n] = 0;
                std::cout << "[" << inet_ntoa(peer.sin_addr) << ":" << ntohs(peer.sin_port) <<"]# " << inbuffer << std::endl;
                std::string echo_string = "[udp_server echo]# ";
                echo_string += inbuffer;
                sendto(_sockfd, echo_string.c_str(), echo_string.size(), 0, (struct sockaddr*)&peer, len);

            }
            else
            {
                LOG(WARNING, "recvfrom, error\n");
            }
        }
    }
    
    ~UdpServer()
    {
        if (_sockfd > 0)
            close(_sockfd);
    }

private:
    int _sockfd;
    uint16_t _localport;
    bool _isrunning;
};